<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Request;
use app\admin\model\Banner;
use app\admin\model\WxappUser;
use app\admin\model\Live;
use app\admin\model\Jieshuo;
use app\admin\model\LiveMsg;
use app\admin\model\WatchHistory;
use app\admin\model\Experience;
use app\admin\model\Project;
use app\admin\model\ExperienceScan;
use app\admin\model\School;

use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Label\Font\Font;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;

/**
 * 回放通知-控制器
 * @author 牧羊人
 * @since 2020/11/19
 * Class Index
 * @package app\admin\controller
 */
class Wxapp extends Backend
{

    // 登录ID
    protected $userId;
    
    /**
     * 登录
     * @return mixed
     * @since 2024/7/22
     * @author zlchen
     */
    public function login(Request $request)
    {
        //根据自己请求数据方式修改
        $code = $request->param('code');
        //得到code换取openid
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxd178efd1b7478ec5&secret=e24a09f03b40513cfcb554905ff2d440&js_code=$code&grant_type=authorization_code";
        $data = $this->curl($url,"get","https");
        if(is_array($data) && isset($data['openid'])){
            // 通过openid去查询wxapp_user表
            $res = WxappUser::where(['openid'=>$data['openid'],'mark'=>1])->find();
            if($res){
                // JWT生成token
                $jwt = new \Jwt();
                $id = $res['id'];
                $token = $jwt->getToken($id);
                return $this->jsonReturn(['code'=>0,'msg'=>'登录成功','data'=>['token'=> $token]]);
            }else{
                return $this->jsonReturn(['code'=>0,'msg'=>'用户不存在','data'=>[]]);
            }
        }
        return $this->jsonReturn($data);
    }
    
    
      /**
     * 保存用户信息
     * @return mixed
     * @since 2024/7/22
     * @author zlchen
     */
    public function saveUserinfo(Request $request)
    {
        //根据自己请求数据方式修改
        $datas = $request->post();
        
        $code = $datas['code'];
        
        unset($datas['code']);
        
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxd178efd1b7478ec5&secret=e24a09f03b40513cfcb554905ff2d440&js_code=$code&grant_type=authorization_code";
        $data = $this->curl($url,"get","https");
        if(is_array($data) && isset($data['openid'])){
            // 通过openid去查询wxapp_user表
            $user = WxappUser::where(['openid'=>$data['openid'],'mark'=>1])->find();
            if($user){
                
                // 设置更新的字段值
                $user->nickname = $datas['nickname'];
                $user->avatar = $datas['avatar'];
                $user->update_time = time();
                 
                // 保存更新的数据
                $result = $user->save();
                
                // JWT生成token
                $jwt = new \Jwt();
                $id = $user['id'];
                $token = $jwt->getToken($id);
                return $this->jsonReturn(['code'=>0,'msg'=>'用户信息更新成功','data'=>['token'=> $token]]);
            }else{
                 $user = new WxappUser();
                 $datas['openid'] = $data['openid'];
                 $datas['create_time'] = time();
                 
                // 保存数据
                $result = $user->save($datas);
                if ($result) {
                    // 获取最后插入的ID
                    $userId = $user->getLastInsID();
                    $code = 0;
                    $msg = '注册成功！';
                    
                    $jwt = new \Jwt();
                    $token = $jwt->getToken($userId);
                    return $this->jsonReturn(['code'=>0,'msg'=>'注册成功','data'=>['token'=> $token]]);
                    
                    
                } else {
                    return $this->jsonReturn(['code'=>1,'msg'=>'注册失败','data'=>[]]);
                }
                
            }
        }else{
            return $this->jsonReturn($data);
        }

       
    }
    
     /**
     * 上传图片（支持多图片上传）
     * 备注：1、单文件：file
     *      2、多文件：file[],file[]
     * @return array
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function uploadImage()
    {
        // 错误提示语
        $error = "";
        // 上传图片
        $result = upload_image('file', '', $error);
        if (!$result) {
            return message($error, false);
        }
        // 多图片上传处理
        $list = [];
        if (is_array($result)) {
            foreach ($result as $val) {
                // $list[] = IMG_URL . $val;
                $list[] = [
                    'url' => $val,
                    'full_url' =>IMG_URL . $val
                ];
            }
        } else {
            $list = [
                'url' => $result,
                'full_url' =>IMG_URL . $result
            ];
        }
        return $this->jsonReturn(message("上传成功", true, $list));
    }
    
    // 轮播图列表
    public function banners()
    {
        $datas = Banner::where(['status'=>1,'mark'=>1])->select();
        
        foreach ($datas as $data){
            $data['image'] = IMG_URL . $data['image'];
        }
          // 结果返回
        $result = [
            'code' => 0, 
            'msg' => 'ok',
            'data' => $datas
            
        ];
        
        return $this->jsonReturn($result);
    }
    
     // 届数列表
    public function jieshuos()
    {
        $datas = Jieshuo::where(['status'=>1,'mark'=>1])->limit(3)->order('sort desc')->select();
          // 结果返回
        $result = [
            'code' => 0, 
            'msg' => 'ok',
            'data' => $datas
            
        ];
        
        return $this->jsonReturn($result);
    }
    
    // 直播列表
    public function lives(Request $request)
    {
        $param = $request->post();
        
        $map[] = ['status', '=', 1];
        $map[] = ['mark', '=', 1];
        
        // 届数
        $jieshuo_id = isset($param['jieshuo_id']) ? (int)$param['jieshuo_id'] : 0;
        if ($jieshuo_id) {
            $map[] = ['jieshuo_id', '=', $jieshuo_id];
        }
        
        // 直播名称
        $name = isset($param['name']) ? trim($param['name']) : '';
        if ($name) {
            $map[] = ['name', 'like', "%{$name}%"];
        }
        $datas = Live::where($map)->order('live_status asc,live_time desc')->select();
        
        // 结果返回
        $result = [
            'code' => 0, 
            'msg' => 'ok',
            'data' => $datas
            
        ];
        
        return $this->jsonReturn($result);
    }
    
     // 直播间详情
    public function liveDetails($live_id)
    {
        $liveInfo = Live::find($live_id);
        
        $liveInfo['image'] = IMG_URL . $liveInfo['image'];
        // 结果返回
        $result = [
            'code' => 0, 
            'msg' => 'ok',
            'data' => $liveInfo
            
        ];
        
        return $this->jsonReturn($result);
        
    }
    
     // 直播间留言
    public function liveroomMessage(Request $request)
    {
        $datas = $request->post();
        // live_id token content msg_time
        
        // 获取Token
        $token = request()->header("Authorization");
        if ($token && strpos($token, 'Bearer ') !== false) {
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $jwt = new \Jwt();
            $userId = $jwt->verifyToken($token);
            if($userId){
                $user = WxappUser::field('id,nickname,avatar,type')->find($userId);
                $liveMsg = [
                    'user_id' => $userId,
                    'nickname' => $user['nickname'],
                    'avatar' => $user['avatar'],
                    'live_id' => $datas['live_id'],
                    'content' => trim($datas['content']),
                    'msg_time' => date('Y-m-d H:i:s')
                    ];
                $res = (new LiveMsg)->save($liveMsg);
                if($res){
                    $result = [
                        'code' => 0, 
                        'msg' => 'success',
                        'data' => []
                    ];
                }else{
                    $result = [
                        'code' => 1, 
                        'msg' => 'fail',
                        'data' => []
                    ];
                }
            }else{
                $result = [
                    'code' => 401, 
                    'msg' => '无效的Token或Token已过期',
                    'data' => []
                ];
            }
            
            
            
        }else{
             $result = [
                'code' => 1, 
                'msg' => 'token认证失败',
                'data' => []
            ];
        }
        
        return $this->jsonReturn($result);
        
    }
    
    // 我的-观看记录
    public function watchHistory()
    {
        // 获取Token
        $token = request()->header("Authorization");
        if ($token && strpos($token, 'Bearer ') !== false) {
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $jwt = new \Jwt();
            $userId = $jwt->verifyToken($token);
            if($userId){
                $user = WxappUser::field('id,nickname,avatar,type')->find($userId);
                $datas = WatchHistory::field('id,user_id,live_id,watch_time')->where(['mark'=>1,'user_id' => $userId])->order('watch_time desc')->select();
                if($datas){
                    
                    foreach ($datas as $data){
                        $liveInfo = Live::field('id,image,name,jieshuo_id,rtmp,flv,stream_id,replay,live_status,viewers,live_time')->find($data['live_id']);
                        
                        $liveInfo['image'] = get_image_url($liveInfo['image']);
                        
                        $data['live_info'] = $liveInfo;
                    }
                    
                    
                }
                
                $result = [
                    'code' => 0, 
                    'msg' => 'ok',
                    'data' => $datas
                ];
            }else{
                $result = [
                    'code' => 401, 
                    'msg' => '无效的Token或Token已过期',
                    'data' => []
                ];
            }
            
        }else{
             $result = [
                'code' => 1, 
                'msg' => 'token认证失败',
                'data' => []
            ];
        }
        
        return $this->jsonReturn($result);
    }
    
    // 获取用户信息
    public function getUserInfo()
    {
        // 获取Token
        $token = request()->header("Authorization");
        if ($token && strpos($token, 'Bearer ') !== false) {
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $jwt = new \Jwt();
            $userId = $jwt->verifyToken($token);
            if($userId){
                $user = WxappUser::field('id,nickname,avatar,type,mobile')->find($userId);
                $user['avatar'] = IMG_URL . $user['avatar'];
                $result = [
                    'code' => 0, 
                    'msg' => 'success',
                    'data' => $user
                ];
            }else{
                $result = [
                    'code' => 401, 
                    'msg' => '无效的Token或Token已过期',
                    'data' => []
                ];
            }
           
        }else{
             $result = [
                'code' => 1, 
                'msg' => 'token认证失败',
                'data' => []
            ];
        }
        
        return $this->jsonReturn($result);
        
    }
    
    // 直播间留言列表
    public function messageList($live_id)
    {
        $datas = LiveMsg::field('id,nickname,avatar,user_id,live_id,content,msg_time')->where(['live_id'=>$live_id])->limit(50)->order('msg_time asc')->select();
        
        foreach ($datas as $data){
            $data['avatar'] = get_image_url($data['avatar']);
        }
        // 结果返回
        $result = [
            'code' => 0, 
            'msg' => 'ok',
            'data' => $datas
            
        ];
        
        return $this->jsonReturn($result);
        
    }
    
    // 直播观看
    public function watchLive(Request $request)
    {
         $datas = $request->post();
        // live_id token content msg_time
        
        // 更新直播间的观看数
        $liveId = getter($datas, "live_id");
        (new Live)->where('id', $liveId)->setInc('viewers');
        
        // 获取Token
        $token = request()->header("Authorization");
        if ($token && strpos($token, 'Bearer ') !== false) {
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $jwt = new \Jwt();
            $userId = $jwt->verifyToken($token);
            if($userId){
                $user = WxappUser::field('id,nickname,avatar,type')->find($userId);
                $watchHistory = new WatchHistory();
                $where = [
                    'user_id' => $userId,
                    'live_id' => $datas['live_id']
                ];
                $exists = $watchHistory->where($where)->find();
                if($exists){
                     // 存在数据，更新时间字段
                    $data = [
                        'watch_time' => date('Y-m-d H:i:s'),
                        'mark' => 1
                        ]; 
                    $res = $watchHistory->where($where)->update($data);
                    if($res){
                        $result = [
                            'code' => 0, 
                            'msg' => 'success',
                            'data' => []
                        ];
                    }else{
                        $result = [
                            'code' => 1, 
                            'msg' => 'fail',
                            'data' => []
                        ];
                    }
                }else{
                    $liveRecord = [
                        'user_id' => $userId,
                        'live_id' => $datas['live_id'],
                        'watch_time' => date('Y-m-d H:i:s')
                    ];
                    
                    $res = $watchHistory->save($liveRecord);
                    if($res){
                        $result = [
                            'code' => 0, 
                            'msg' => 'success',
                            'data' => []
                        ];
                    }else{
                        $result = [
                            'code' => 1, 
                            'msg' => 'fail',
                            'data' => []
                        ];
                    }
                }
            }else{
                $result = [
                    'code' => 401, 
                    'msg' => '无效的Token或Token已过期',
                    'data' => []
                ];
            }
            
        }else{
             $result = [
                'code' => 1, 
                'msg' => 'token认证失败',
                'data' => []
            ];
        }
        
        return $this->jsonReturn($result);
    }
    
    // 删除观看记录
    public function watchRecordsDel()
    {
        // 获取Token
        $token = request()->header("Authorization");
        if ($token && strpos($token, 'Bearer ') !== false) {
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $jwt = new \Jwt();
            $userId = $jwt->verifyToken($token);
            if($userId){
                $user = WxappUser::field('id,nickname,avatar,type')->find($userId);
        
                // 参数
                $param = request()->param();
                // 记录ID
                $ids = getter($param, "id");
                $res = (new WatchHistory)->deleteDAll($ids);
                if($res){
                    $result = [
                        'code' => 0, 
                        'msg' => 'success',
                        'data' => []
                    ];
                }else{
                    $result = [
                        'code' => 1, 
                        'msg' => 'fail',
                        'data' => []
                    ];
                }
            }else{
                $result = [
                    'code' => 401, 
                    'msg' => '无效的Token或Token已过期',
                    'data' => []
                ];
            }
            
        }else{
             $result = [
                'code' => 1, 
                'msg' => 'token认证失败',
                'data' => []
            ];
        }
        
        return $this->jsonReturn($result);
    }
    
    // 可体验项目列表
    public function experiences()
    {
        // 最新的体验
        $experience = Experience::where(['status'=>1,'mark'=>1])->order('sort', 'desc')->find();
        
        if($experience){
            $project_ids = $experience['project_ids'];
            $ids = explode(",", $project_ids);
            $projects = Project::field('id,name,cover,intro,sort')->where('id', 'in', $ids)->order('sort asc')->select();
            
            foreach($projects as $project){
                $project['experience_id'] = $experience['id'];
                // 202408021800 add zlchen
                $project['start_time'] =  $experience['start_time'];
                $project['end_time'] =  $experience['end_time'];
               
            }
            
            $result = [
                'code' => 0, 
                'msg' => 'ok',
                'data' => $projects
            ];
        }else{
             $result = [
                'code' => 1, 
                'msg' => '无可体验的项目',
                'data' => []
            ];
        }
        
        return $this->jsonReturn($result);
        
    }
    
    // 活动、体验列表
    public function experienceList()
    {
       // 参数
       $param = request()->param();
       
       $map[] = ['status', '=', 1];
       $map[] = ['mark', '=', 1];
        
       // 体验名称
       $name = isset($param['name']) ? trim($param['name']) : '';
       if ($name) {
          $map[] = ['name', 'like', "%{$name}%"];
       }
       
        // 最新的体验
        $experiences = Experience::field('id,name,project_ids,start_time,end_time,status,sort')->where($map)->order('sort', 'desc')->select();
        
        foreach($experiences as $experience){
            $project_ids = $experience['project_ids'];
            $ids = explode(",", $project_ids);
            $experience['count'] = count($ids);
            
            // 格式化日期
            $dateTime = \DateTime::createFromFormat('Y-m-d H:i:s', $experience['start_time']);
            $experience['start_time'] = $dateTime->format('Y-m-d H:i');
            
            $dateTime2 = \DateTime::createFromFormat('Y-m-d H:i:s', $experience['end_time']);
            $experience['end_time'] = $dateTime2->format('Y-m-d H:i');
            
        }
        
        $result = [
                'code' => 0, 
                'msg' => 'ok',
                'data' => $experiences
            ];
        
        return $this->jsonReturn($result);
        
    }
    
    // 绑定手机号
    public function bind()
    {
        // 参数
        $param = request()->param();
        
        // 获取Token
        $token = request()->header("Authorization");
        if ($token && strpos($token, 'Bearer ') !== false) {
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $jwt = new \Jwt();
            $userId = $jwt->verifyToken($token);
            
            if($userId){
                // 注册的老师账户
                $mobile = getter($param, "mobile");
                $openid = WxappUser::where(['type'=>2,'mobile'=>$mobile,'mark'=>1])->value('openid');
                if($openid){
                    $result = [
                        'code' => 1, 
                        'msg' => '手机号已被绑定',
                        'data' => []
                    ];
                }else{
                    
                    $teacher = WxappUser::field('id,realname,type')->where(['type'=>2,'mobile'=>$mobile,'mark'=>1])->find();
                
                    if($teacher){
                        $res = WxappUser::where(['id'=>$userId])->update(['type'=>2,'mobile'=>$mobile,'realname'=>$teacher['realname'],'update_time'=>time()]);
                        if($res){
                            $teacher->delete();
                        }
                        
                        $result = [
                            'code' => 0, 
                            'msg' => '绑定成功',
                            'data' => []
                        ];
                        
                    }else{
                        
                        $ptuser = WxappUser::where(['type'=>1,'mobile'=>$mobile,'mark'=>1])->value('openid');
                        if($ptuser){
                            $res = WxappUser::where(['id'=>$userId])->update(['type'=>2,'update_time'=>time()]);
                            if($res){
                                $result = [
                                    'code' => 0, 
                                    'msg' => '绑定成功',
                                    'data' => []
                                ];
                            }else{
                                $result = [
                                    'code' => 1, 
                                    'msg' => '无法绑定,请检查老师账号是否正确',
                                    'data' => []
                                ];
                            }
                        }else{
                          
                            $result = [
                                'code' => 1, 
                                'msg' => '无法绑定,请检查老师账号是否正确',
                                'data' => []
                            ];
                        }
                         
                    }
                    
                }
            }else{
                $result = [
                    'code' => 401, 
                    'msg' => '无效的token或token已过期',
                    'data' => []
                ];
            }
            
       
            
        }else{
             $result = [
                'code' => 1, 
                'msg' => 'token认证失败',
                'data' => []
            ];
        }
        
        return $this->jsonReturn($result);
    }
    
    
     // 手机号解绑
    public function unbind()
    {
        // 获取Token
        $token = request()->header("Authorization");
        if ($token && strpos($token, 'Bearer ') !== false) {
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $jwt = new \Jwt();
            $userId = $jwt->verifyToken($token);
            if($userId){
                $res =  WxappUser::where(['id'=>$userId])->update(['type'=>1,'update_time'=>time()]);
                if($res){
                    $result = [
                        'code' => 0, 
                        'msg' => '解绑成功',
                        'data' => []
                    ];
                }else{
                     $result = [
                        'code' => 1, 
                        'msg' => '无法解绑,请联系管理员',
                        'data' => []
                    ];
                }
            }else{
                $result = [
                    'code' => 401, 
                    'msg' => '无效的token或token已过期',
                    'data' => []
                ];
            }
            
        }else{
             $result = [
                'code' => 1, 
                'msg' => 'token认证失败',
                'data' => []
            ];
        }
        
        return $this->jsonReturn($result);
    }
    
    // 获取Token
    public function token($user_id)
    {
         // JWT生成token
        $jwt = new \Jwt();
        $token = $jwt->getToken($user_id);
        return $this->jsonReturn(['code'=>0,'msg'=>'ok','data'=>['token'=> $token]]);
    }
    
    // 老师端-体验-扫一扫
    public function experienceScan()
    {
         // 参数
        $param = request()->param();
        
        // 获取Token
        $token = request()->header("Authorization");
        if ($token && strpos($token, 'Bearer ') !== false) {
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $jwt = new \Jwt();
            $userId = $jwt->verifyToken($token);
            if($userId){
                $param['scan_time'] = time();
                // 202408021145 add zlchen
                $param['scan_date'] = date('Y-m-d',time());
                $param['user_id'] = $userId;
                //$param['school_id'] = School::where(['name'=>$param['school_name']])->value('id');
                $res =  (new ExperienceScan())->save($param);
                if($res){
                    $result = [
                        'code' => 0, 
                        'msg' => '扫码成功',
                        'data' => []
                    ];
                }else{
                     $result = [
                        'code' => 1, 
                        'msg' => '提交失败',
                        'data' => []
                    ];
                }
            }else{
                $result = [
                    'code' => 401, 
                    'msg' => '无效的token或token已过期',
                    'data' => []
                ];
            }
            
        }else{
             $result = [
                'code' => 1, 
                'msg' => 'token认证失败',
                'data' => []
            ];
        }
        
        return $this->jsonReturn($result);
        
        
    }
    
    // 老师端-体验-统计
    public function experienceStatistics()
    {
         // 参数
        $param = request()->param();
        
        // 实例化模型
        $experienceScan = new ExperienceScan();
        
       // 学校名称
       $name = isset($param['school_name']) ? trim($param['school_name']) : '';
       if ($name) {
          $map[] = ['school_name', 'like', "%{$name}%"];
       }
       
       $map[] = ['experience_id', '=', $param['experience_id']];
       $map[] = ['mark', '=', 1];
         
        // 分组并统计每组的用户数
        $groupedSchool = $experienceScan->field('school_id,school_name,COUNT(DISTINCT project_id) as project_count, COUNT(scan_time) as scan_sum')
                              ->where($map)
                              ->group('school_id')
                              ->select();
        
        $result = [
                'code' => 0, 
                'msg' => 'ok',
                'data' => $groupedSchool
            ];
        
        return $this->jsonReturn($result);
        
        
    }
    
    
    // 老师端-统计详情
    public function statisticsDetail()
    {
         // 参数
        $param = request()->param();
        
        // 实例化模型
        $experienceScan = new ExperienceScan();
         
        // 分组并统计每组的用户数
        $groupedProject = $experienceScan->field('project_id, COUNT(scan_time) as scan_sum')
                              ->where(['experience_id'=>$param['experience_id'],'school_id'=>$param['school_id']])
                              ->group('project_id')
                              ->select();
                              
        foreach ($groupedProject as $project){
            $project['project_name'] = Project::where(['id'=>$project['project_id']])->value('name');
        }
        
        $result = [
                'code' => 0, 
                'msg' => 'ok',
                'data' => $groupedProject
            ];
        
        return $this->jsonReturn($result);
        
        
    }
    
    // 老师端-我的-扫码记录
    public function scanLogs()
    {
    // 参数
       $param = request()->param();
       
       // 学校名称
       $name = isset($param['school_name']) ? trim($param['school_name']) : '';
       if ($name) {
          $map[] = ['school_name', 'like', "%{$name}%"];
       }
       
       // 项目ID
       $project_id = isset($param['project_id']) ? (int)$param['project_id'] : 0;
       if ($project_id) {
          $map[] = ['project_id', '=', $project_id];
       }
       
       // 扫码日期
       $scan_date = isset($param['scan_date']) ? $param['scan_date'] : '0000-00-00';
       if ($scan_date) {
          $map[] = ['scan_date', '=', $scan_date];
       }
        
        // 获取Token
        $token = request()->header("Authorization");
        if ($token && strpos($token, 'Bearer ') !== false) {
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $jwt = new \Jwt();
            $userId = $jwt->verifyToken($token);
            if($userId){
                
                $map[] = ['user_id','=',$userId];
                
                $datas = ExperienceScan::field('create_user,create_time,update_user,update_time,mark',true)->where($map)->order('scan_time desc')->select();
                foreach ($datas as $data){
                    $data['project_name'] = Project::where(['id'=>$data['project_id']])->value('name');
                    $data['user_name'] = WxappUser::where(['id'=>$data['user_id']])->value('realname');
                    $data['scan_date'] = date('Y-m-d H:i:s',$data['scan_time']);
                }
                $result = [
                    'code' => 0, 
                    'msg' => 'ok',
                    'data' => $datas
                ];
                
            }else{
                $result = [
                    'code' => 401, 
                    'msg' => '无效的token或token已过期',
                    'data' => []
                ];
            }
            
        }else{
             $result = [
                'code' => 1, 
                'msg' => 'token认证失败',
                'data' => []
            ];
        }
        
        return $this->jsonReturn($result);
        
        
    }
    
    // 所有项目列表
    public function allProject()
    {
       
        $projects = Project::field('id,name,cover,intro,sort')->where(['mark'=>1,'status'=>1])->order('sort asc')->select();
        
        $result = [
            'code' => 0, 
            'msg' => 'ok',
            'data' => $projects
        ];
        
        return $this->jsonReturn($result);
        
    }
    
    public function test()
    {

        $writer = new PngWriter();
        
        $str = json_encode(['id'=>1,'name'=>'奥斯翰外国语学校']);
        
        $qrCode = QrCode::create($str)
        // 内容编码
        ->setEncoding(new Encoding('UTF-8'))
        // 容错等级
        ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())
        // 内容区域大小
        ->setSize(350)
        // 内容区域外边距
        ->setMargin(10)
        // 内容圆形块尺寸模型
        ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())
        // 内容颜色
        ->setForegroundColor(new Color(0, 0, 0))
        // 背景颜色
        ->setBackgroundColor(new Color(255, 255, 255));
        // 二维码logo logo
        $logo = Logo::create(__DIR__ . '/logo.png')
        ->setResizeToWidth(50);
        // 二维码下方文字 label
        $label = Label::create('奥斯翰外国语学校')
        ->setTextColor(new Color(255, 0, 0));
        // 生成二维码数据对象(后面两个参数都是可选的)
        $result = $writer->write($qrCode, $logo, $label);
        
        // 1.直接输出在浏览器中
        ob_end_clean(); //处理在TP框架中显示乱码问题
        header('Content-Type: ' . $result->getMimeType());
        echo $result->getString();
        // 2.将二维码图片保存到本地服务器
        $result->saveToFile(__DIR__ . '/qrcode.png');
        // 3.返回 base64 格式的图片
        $dataUri = $result->getDataUri();
        echo "<img src='{$dataUri}'>";
 
    }
    
    /* 图片下载 */
    public function download()
    {
        $file_url = IMG_PATH . '/school/'. md5(1) . '.png'; // 文件路径
        header("Content-Type: image/png");
        header("Content-Disposition: attachment; filename=" . "jianghe.png");
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header("Content-Length: " . filesize($file_url));
        @readfile($file_url);
    }

    //封装curl 抓取数据
    public function curl($url, $method = "get", $type = "http", $data = "")
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if ($type == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不做服务器认证
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不做客户端认证
        }
        if ($method == "post") {
            curl_setopt($ch, CURLOPT_POST, true);//设置请求是POST方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置POST请求的数据
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        curl_close($ch);
        return json_decode($data, true);
    }

}